<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统 - 仪表盘</title>
    <link rel="stylesheet" href="../styles/styles-main.css">
    <link rel="stylesheet" href="../styles/dashboard.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="../modules/module-loader.js"></script>
    <script src="../modules/core-modules.js"></script>
    <script>
        // 动态加载仪表盘所需模块
        document.addEventListener('DOMContentLoaded', async function() {
            try {
                await moduleLoader.loadModules([
                    ['api-client', '../scripts/api-client.js'],
                    ['data-manager', '../scripts/data-manager.js'],
                    ['sync-system', '../scripts/sync-system.js'],
                    ['navbar-main', '../scripts/navbar-main.js'],
                    ['sidebar-manager', '../scripts/sidebar-manager.js'],
                    ['page-sync-manager', '../scripts/page-sync-manager.js'],
                    ['dashboard-main', '../scripts/dashboard-main.js']
                ]);
                
                // 确保侧边栏和导航栏已初始化
                if (window.sidebarManager) {
                    console.log('侧边栏管理器已初始化');
                }
                
                // 初始化仪表盘
                if (typeof DashboardManager !== 'undefined') {
                    const dashboard = new DashboardManager();
                    dashboard.init();
                }
            } catch (error) {
                console.error('模块加载失败:', error);
            }
        });
    </script>
</head>
<body>
    <div id="navbar-container"></div>
    
    <div class="container">
        <!-- 侧边栏将由 sidebar-manager.js 动态生成 -->
        
        <main class="content">
            <div class="content-header">
                <h1>仪表盘总览</h1>
                <p>实时监控系统关键指标和业务数据</p>
            </div>
            
            <div class="dashboard-container">
                <!-- 顶部状态栏 -->
                <div class="status-bar">
                    <div class="status-info">
                        <div class="time-display">
                            <span>当前时间：</span>
                            <span id="currentTime">--:--:--</span>
                        </div>
                    </div>
                </div>

                <!-- 关键指标卡片 -->
                <div class="metrics-grid">
                    
                    <!-- 访客数据 -->
                    <div class="metric-card success">
                        <div class="metric-header">
                            <div class="metric-title">今日访客</div>
                            <i class="fas fa-users"></i>
                        </div>
                        <div class="metric-value" id="todayVisitors">0</div>
                        <div class="metric-change positive" id="visitorsChange">
                            <i class="fas fa-arrow-up"></i> %
                        </div>
                        <div class="metric-trend">较昨日</div>
                    </div>
                    
                    <div class="metric-card info">
                        <div class="metric-header">
                            <div class="metric-title">页面浏览量</div>
                            <i class="fas fa-eye"></i>
                        </div>
                        <div class="metric-value" id="pageViews">0</div>
                        <div class="metric-change" id="pageViewsChange">
                            <i class="fas fa-minus"></i> %
                        </div>
                        <div class="metric-trend">较上周</div>
                    </div>
                    
                    <!-- 留言订阅数据 -->
                    <div class="metric-card warning">
                        <div class="metric-header">
                            <div class="metric-title">新留言</div>
                            <i class="fas fa-comments"></i>
                        </div>
                        <div class="metric-value" id="newMessages">0</div>
                        <div class="metric-change" id="messagesChange">
                            <i class="fas fa-minus"></i> %
                        </div>
                        <div class="metric-trend">待处理</div>
                    </div>
                    
                    <div class="metric-card success">
                        <div class="metric-header">
                            <div class="metric-title">邮件订阅</div>
                            <i class="fas fa-envelope"></i>
                        </div>
                        <div class="metric-value" id="emailSubscribers">0</div>
                        <div class="metric-change positive" id="subscribersChange">
                            <i class="fas fa-arrow-up"></i> %
                        </div>
                        <div class="metric-trend">总订阅数</div>
                    </div>
                    
                    <!-- 博客数据 -->
                    <div class="metric-card info">
                        <div class="metric-header">
                            <div class="metric-title">博客文章</div>
                            <i class="fas fa-newspaper"></i>
                        </div>
                        <div class="metric-value" id="blogArticles">0</div>
                        <div class="metric-change" id="articlesChange">
                            <i class="fas fa-minus"></i> %
                        </div>
                        <div class="metric-trend">已发布</div>
                    </div>
                    
                    <div class="metric-card success">
                        <div class="metric-header">
                            <div class="metric-title">博客阅读量</div>
                            <i class="fas fa-book-reader"></i>
                        </div>
                        <div class="metric-value" id="blogReads">0</div>
                        <div class="metric-change positive" id="readsChange">
                            <i class="fas fa-arrow-up"></i> %
                        </div>
                        <div class="metric-trend">本月累计</div>
                    </div>
                </div>




            </div>
        </main>
    </div>

    <script>
        // 全局初始化函数
        function initializeDashboard() {
            try {
                console.log('开始初始化仪表盘系统...');
                
                // 检查仪表盘管理器是否已存在（由dashboard-main.js初始化）
                if (!window.dashboardManager) {
                    console.warn('仪表盘管理器尚未初始化，等待dashboard-main.js加载');
                    // 返回true让页面继续加载，dashboard-main.js会在DOM加载完成后初始化
                    return true;
                }
                
                console.log('✅ 仪表盘系统初始化完成');
                return true;
                
            } catch (error) {
                console.error('❌ 仪表盘系统初始化失败:', error);
                
                // 即使初始化失败，也设置一个基本的dashboardManager对象
                window.dashboardManager = {
                    loadDashboardData: function() {
                        console.log('系统正在初始化中，请稍后重试');
                    },
                    updateMetricsDisplay: function() {
                        console.log('系统正在初始化中，请稍后重试');
                    }
                };
                
                return false;
            }
        }

        // 仪表盘页面同步初始化
        class DashboardSync {
            constructor() {
                this.syncManager = window.pageSyncManager;
                this.init();
            }

            init() {
                // 注册页面同步
                this.pageState = this.syncManager.registerPage('dashboard', {
                    dataPaths: [
                        'metrics',
                        'charts',
                        'system.currentCurrency',
                        'system.currentLanguage',
                        'alerts'
                    ],
                    highFrequency: true,
                    autoSync: true
                });

                // 设置增量更新处理器
                this.setupIncrementalHandlers();
                
                // 监听同步事件
                this.setupSyncEventListeners();
                
                console.log('仪表盘同步系统已初始化');
            }

            setupIncrementalHandlers() {
                // 为仪表盘管理器添加增量更新支持
                if (window.dashboardManager) {
                    window.dashboardManager.handleIncrementalUpdate = async (update) => {
                        await this.handleIncrementalUpdate(update);
                    };
                    
                    window.dashboardManager.reloadData = async () => {
                        await this.performFullSync();
                    };
                }
            }

            setupSyncEventListeners() {
                // 监听手动同步事件
                document.addEventListener('manualSyncRequired', (event) => {
                    if (event.detail.pageId === 'dashboard') {
                        this.triggerManualSync();
                    }
                });

                // 监听错误恢复事件
                document.addEventListener('errorRecoveryRequired', (event) => {
                    if (event.detail.pageId === 'dashboard') {
                        this.performErrorRecovery();
                    }
                });

                // 监听页面数据重新加载事件
                document.addEventListener('pageDataReload', (event) => {
                    if (event.detail.pageId === 'dashboard') {
                        this.reloadDashboardData(event.detail);
                    }
                });
            }

            async handleIncrementalUpdate(update) {
                console.log('处理仪表盘增量更新:', update);
                
                try {
                    switch (update.path) {
                        case 'metrics':
                            await this.updateMetricsIncrementally(update.value);
                            break;
                        case 'charts':
                            await this.updateChartsIncrementally(update.value);
                            break;
                        case 'system.currentCurrency':
                            await this.updateCurrency(update.value);
                            break;
                        case 'system.currentLanguage':
                            await this.updateLanguage(update.value);
                            break;
                        case 'alerts':
                            await this.updateAlerts(update.value);
                            break;
                    }
                    
                    this.showSyncStatus('数据已同步', 'success');
                    
                } catch (error) {
                    console.error('增量更新失败:', error);
                    this.showSyncStatus('同步失败', 'error');
                }
            }

            async updateMetricsIncrementally(newMetrics) {
                if (window.dashboardManager && window.dashboardManager.updateMetricsDisplay) {
                    window.dashboardManager.updateMetricsDisplay(newMetrics);
                }
            }

            async updateChartsIncrementally(newCharts) {
                if (window.dashboardManager && window.dashboardManager.updateCharts) {
                    window.dashboardManager.updateCharts(newCharts);
                }
            }

            async updateCurrency(newCurrency) {
                if (window.dashboardManager && window.dashboardManager.changeCurrency) {
                    window.dashboardManager.changeCurrency(newCurrency);
                }
            }

            async updateLanguage(newLanguage) {
                if (window.dashboardManager && window.dashboardManager.changeLanguage) {
                    window.dashboardManager.changeLanguage(newLanguage);
                }
            }

            async updateAlerts(newAlerts) {
                if (window.dashboardManager && window.dashboardManager.updateAlerts) {
                    window.dashboardManager.updateAlerts(newAlerts);
                }
            }

            async performFullSync() {
                console.log('执行仪表盘全量同步');
                
                this.showSyncStatus('正在同步数据...', 'syncing');
                
                try {
                    if (window.dashboardManager && window.dashboardManager.loadDashboardData) {
                        await window.dashboardManager.loadDashboardData();
                    }
                    
                    this.showSyncStatus('同步完成', 'success');
                    
                } catch (error) {
                    console.error('全量同步失败:', error);
                    this.showSyncStatus('同步失败', 'error');
                }
            }

            triggerManualSync() {
                // 显示手动同步按钮或提示
                this.showManualSyncPrompt();
            }

            showManualSyncPrompt() {
                // 创建手动同步提示界面
                const prompt = document.createElement('div');
                prompt.className = 'sync-prompt';
                prompt.innerHTML = `
                    <div style="position: fixed; top: 20px; right: 20px; background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 4px; padding: 15px; z-index: 1000; max-width: 300px;">
                        <p style="margin: 0 0 10px 0; color: #856404;">检测到数据未同步</p>
                        <button onclick="dashboardSync.manualSyncNow()" style="background: #007bff; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer; margin-right: 10px;">立即同步</button>
                        <button onclick="this.parentElement.remove()" style="background: #6c757d; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer;">忽略</button>
                    </div>
                `;
                
                document.body.appendChild(prompt);
            }

            async manualSyncNow() {
                await this.performFullSync();
                // 移除提示
                const prompt = document.querySelector('.sync-prompt');
                if (prompt) prompt.remove();
            }

            async performErrorRecovery() {
                console.log('执行仪表盘错误恢复');
                
                this.showSyncStatus('正在恢复数据...', 'recovering');
                
                try {
                    // 清空本地缓存数据
                    localStorage.removeItem('dashboard-cache');
                    
                    // 重新加载所有数据
                    await this.performFullSync();
                    
                    this.showSyncStatus('恢复完成', 'success');
                    
                } catch (error) {
                    console.error('错误恢复失败:', error);
                    this.showSyncStatus('恢复失败', 'error');
                }
            }

            async reloadDashboardData(detail) {
                console.log('重新加载仪表盘数据:', detail);
                await this.performFullSync();
            }

            showSyncStatus(message, type) {
                // 更新页面上的同步状态显示
                const statusElement = document.getElementById('syncStatus') || this.createStatusElement();
                
                statusElement.textContent = message;
                statusElement.className = `sync-status sync-status-${type}`;
                
                // 3秒后自动隐藏成功消息
                if (type === 'success') {
                    setTimeout(() => {
                        statusElement.style.display = 'none';
                    }, 3000);
                }
            }

            createStatusElement() {
                const element = document.createElement('div');
                element.id = 'syncStatus';
                element.style.cssText = `
                    position: fixed;
                    top: 10px;
                    right: 10px;
                    padding: 10px 15px;
                    border-radius: 4px;
                    font-size: 12px;
                    z-index: 1000;
                    display: none;
                `;
                
                document.body.appendChild(element);
                return element;
            }

            getSyncStatus() {
                return this.syncManager.getSyncStatus('dashboard');
            }

            destroy() {
                this.syncManager.destroyPageSync('dashboard');
            }
        }

        // 创建全局仪表盘同步实例
        let dashboardSync;

        // 初始化函数
        function initDashboardSync() {
            dashboardSync = new DashboardSync();
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM加载完成，开始初始化仪表盘系统...');
            
            // 首先初始化基础系统
            const initSuccess = initializeDashboard();
            
            if (initSuccess) {
                // 等待仪表盘管理器初始化完成（由dashboard-main.js负责）
                const waitForDashboardManager = setInterval(() => {
                    if (window.dashboardManager && typeof window.dashboardManager.loadDashboardData === 'function') {
                        clearInterval(waitForDashboardManager);
                        console.log('仪表盘管理器已就绪，开始初始化同步系统');
                        initDashboardSync();
                    }
                }, 100);
                
                // 设置超时（5秒后放弃等待）
                setTimeout(() => {
                    clearInterval(waitForDashboardManager);
                    if (!window.dashboardManager) {
                        console.warn('仪表盘管理器初始化超时，使用回退模式');
                        initDashboardSync();
                    }
                }, 5000);
            } else {
                console.warn('基础系统初始化失败，跳过同步系统初始化');
            }
        });

        // 导出到全局作用域
        window.dashboardSync = dashboardSync;
    </script>
    
    <script>
        // 数据同步演示功能
        let syncDemoManager = {
            init() {
                this.setupSyncMonitoring();
                this.setupDemoControls();
            },
            
            setupSyncMonitoring() {
                // 监控数据管理器状态
                setInterval(() => {
                    const metrics = window.dataManager?.getPerformanceMetrics();
                    if (metrics) {
                        const subscriberEl = document.getElementById('subscriberCount');
                        const queueEl = document.getElementById('updateQueueSize');
                        const dataSizeEl = document.getElementById('dataSize');
                        
                        if (subscriberEl) subscriberEl.textContent = metrics.subscriberCount;
                        if (queueEl) queueEl.textContent = metrics.updateQueueSize;
                        if (dataSizeEl) dataSizeEl.textContent = (metrics.stateSize / 1024).toFixed(2) + ' KB';
                    }
                }, 1000);
            },
            
            setupDemoControls() {
                // 设置最后更新时间
                this.updateLastSyncTime();
            },
            
            updateLastSyncTime() {
                const now = new Date();
                const lastUpdateEl = document.getElementById('lastUpdate');
                if (lastUpdateEl) {
                    lastUpdateEl.textContent = '最后更新: ' + now.toLocaleTimeString('zh-CN');
                }
            }
        };
        
        // 演示控制函数
        function updateVisitorData() {
            const newVisitors = Math.floor(Math.random() * 300) + 200;
            const change = (Math.random() * 15 - 5).toFixed(1);
            
            window.dataManager.setState('metrics.todayVisitors', newVisitors);
            window.dataManager.setState('metrics.visitorsChange', parseFloat(change));
            
            syncDemoManager.updateLastSyncTime();
            showSyncMessage('访客数据已更新');
        }
        
        function updateBlogData() {
            const newReads = Math.floor(Math.random() * 2000) + 2000;
            const change = (Math.random() * 12 - 4).toFixed(1);
            
            window.dataManager.setState('metrics.blogReads', newReads);
            window.dataManager.setState('metrics.readsChange', parseFloat(change));
            
            syncDemoManager.updateLastSyncTime();
            showSyncMessage('博客数据已更新');
        }
        
        function resetAllData() {
            const initialData = {
                // 访客数据
                todayVisitors: 350,
                visitorsChange: 0,
                pageViews: 1500,
                pageViewsChange: 0,
                
                // 留言订阅数据
                newMessages: 12,
                messagesChange: 0,
                emailSubscribers: 750,
                subscribersChange: 0,
                
                // 博客数据
                blogArticles: 35,
                articlesChange: 0,
                blogReads: 3500,
                readsChange: 0
            };
            
            window.dataManager.setState('metrics', initialData);
            syncDemoManager.updateLastSyncTime();
            showSyncMessage('数据已重置为初始状态');
        }
        
        function showSyncMessage(message) {
            const statusElement = document.getElementById('syncStatus');
            statusElement.textContent = message;
            statusElement.style.color = '#28a745';
            
            setTimeout(() => {
                statusElement.textContent = '数据同步正常';
                statusElement.style.color = '';
            }, 3000);
        }
        
        // 初始化演示功能
        document.addEventListener('DOMContentLoaded', function() {
            syncDemoManager.init();
            // initMobileMenu(); // 管理端专为桌面端设计，移除移动端菜单功能
        });
    </script>
    
    <script>
        // 管理端桌面端优化 - 移除移动端菜单功能
        // 管理端专为桌面端设计，提供更好的桌面体验
        
        // 桌面端优化：增强侧边栏交互
        document.addEventListener('DOMContentLoaded', function() {
            // 为侧边栏菜单项添加桌面端悬停效果
            const menuItems = document.querySelectorAll('.sidebar a');
            menuItems.forEach(item => {
                item.addEventListener('mouseenter', function() {
                    this.style.transform = 'translateX(5px)';
                });
                item.addEventListener('mouseleave', function() {
                    this.style.transform = 'translateX(0)';
                });
            });
            
            // 简单的时间显示函数
            function updateTime() {
                const now = new Date();
                const timeString = now.toLocaleTimeString('zh-CN');
                const timeElement = document.getElementById('currentTime');
                if (timeElement) {
                    timeElement.textContent = timeString;
                }
            }
            
            // 立即更新时间并每秒更新
            updateTime();
            setInterval(updateTime, 1000);
        });
    </script>
</body>
</html>